﻿using System;
using System.Configuration;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using Common;

public partial class website_admin_insurance_ordersettings : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;
        PageBegin();

        switch (RequestBase.GetFormString("otype"))
        {
            case "fowardingto":
                FowardingTo();
                break;
            case "sendshipmentnotice":
                SendShipmentNotice();
                break;
            case "loadingshipmentlist":
                LoadShipmentList();
                break;
        }

        switch (RequestBase.GetFormString("____EVENTTARGET"))
        {
            case "invalid":
                UpdateStatus(-1);
                break;
            case "paymentsettings": 
                UpdateStatus(1);
                break;
        }

        if (!IsPostBack)
        {
            InitControlValuesByPost();
            txtFowardingToEmailList.Value = ConfigurationManager.AppSettings["ForwardingEmail"];
        }
    }

    void UpdateStatus(int status)
    {
        Model.Insurance.InsurancePolicyBase _obj = BLL.Insurance.InsurancePolicyBase.GetObjById(RequestBase.GetQueryString("objectid"));

        if (_obj.StatusCode == status)
        {
            divErrorMsg.Style.Add("display", "");
            divErrorMsg.InnerHtml = string.Format(divErrorMsg.InnerHtml, "<li style=\"background: none;\">订单状态已设置，不允许重复操作！</li>");
        }
        else
        {
            string res = BLL.Insurance.InsurancePolicyBase.UpdateStatus(_obj.OrderNumber, this.SystemUserId, status);
            if (res.Split('|')[0] == "succeeded")
            {
                JScript.AlertAndRedirect("设置成功!", RequestBase.GetUrl());
            }
            else
            {
                divErrorMsg.Style.Add("display", "");
                divErrorMsg.InnerHtml = string.Format(divErrorMsg.InnerHtml, "<li style=\"background: none;\">" + res + "</li>");
            }
        }
    }

    #region 保单信息显示
    void InitControlValuesByPost()
    {
        Model.Insurance.InsurancePolicyBase _obj = BLL.Insurance.InsurancePolicyBase.GetObjById(HttpUtility.UrlDecode(RequestBase.GetQueryString("objectid")));
        #region 显示
        lblOrderDate.Text = _obj.OrderDate.ToString("yyyy-MM-dd");

        lblOrderNumber.Text = _obj.OrderNumber;

        lblOrderStatus.Text = _obj.StatusCode.ToString().Replace("-1", "已作废").Replace("0", "新增").Replace("1", "已付款").Replace("2", "已发快递");

        lblTotalAmount.Text = _obj.TotalAmount.ToString();
        lblPersonQuantity.Text = _obj.PersonQuantity.ToString();

        lblProductName.Text = _obj.ProductName;
        lblProductItemName.Text = _obj.ProductItemName;
        lblEmail.Text = _obj.Email;
        lblPhone.Text = _obj.Phone;
        lblPrice.Text = _obj.Price.ToString();
        lblStartDate.Text = _obj.GetStartDate.ToString("yyyy-MM-dd");
        lblEndDate.Text = _obj.EndDate.ToString("yyyy-MM-dd");
        lblDestination.Text = BLL.Sys.EnumItem.GetTextByValue("DestCountryName", _obj.DestCountryName);
        lblPlicyType.Text = BLL.Sys.EnumItem.GetTextByValue("CJType", _obj.CJType);

        lblTName.Text = _obj.TName;
        lblTNameEn.Text = _obj.ETName;
        lblTBirthday.Text = _obj.TBirtyday.ToString("yyyy-MM-dd");
        lblTSex.Text = _obj.TSex.Replace("1", "女").Replace("0", "男");
        lblTIDType.Text = BLL.Sys.EnumItem.GetTextByValue("IDType", _obj.TIDType);
        lblTIDNo.Text = _obj.TIDNo;
        lblTAge.Text = _obj.TAge;

        lblInvoice.Text = (_obj.Invoice) ? "是" : "否";
        lblInvoiceRecipient.Text = _obj.InvoiceRecipient;
        lblInvoicePhone.Text = _obj.InvoicePhone;
        lblInvoiceTitle.Text = _obj.InvoiceTitle;
        lblInvoiceAddress.Text = _obj.InvoiceAddress;

        lblInvoiceFee.Text = _obj.InvoiceFee.ToString();
        lblExpressType.Text = _obj.ExpressType;
        lblSalesTypeCode.Text = _obj.SalesTypeCode.ToString().Replace("1", "电子保单(PDF)").Replace("2", "纸质保单");

        txtShipmentType.Value = _obj.ExpressType;
        txtNoticeContent.Value = string.Format("您的订单{0}的相关资料已寄出，快递单号：expressnumber，快递公司为：{1}，预计2日后到达，收件人为{2}，联系电话{3}，请注意查收。", _obj.OrderNumber, _obj.ExpressType, _obj.InvoiceRecipient, _obj.InvoicePhone);
        txtShipmentDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
        txtOrderNumber.Value = _obj.OrderNumber;
        txtEmail.Value = _obj.Email;
        txtPhone.Value = _obj.Phone;
        txtPhoneNumbers.Value = _obj.Phone;

        txtInvoice.Value = _obj.Invoice ? "1" : "0";
        txtExpressType.Value = _obj.ExpressType;
        txtSalesTypeCode.Value = _obj.SalesTypeCode.ToString();
        lblQuantity.Text = _obj.PersonQuantity.ToString();

        PolicyholdersListDataBind(_obj);
        #endregion
    }
    void PolicyholdersListDataBind(Model.Insurance.InsurancePolicyBase _obj)
    {
        string[] fields = new string[] { "Name", "NameEn", "IDType", "IDNo", "Sex", "Birthday", "Age" };
        string[] fieldstype = new string[] { "System.String", "System.String", "System.String", "System.String", "System.String", "System.String", "System.String" };
        DataTable dat = (new DataTableUtils()).BuildingDTStruct("PolicyholdersDAT", fields, fieldstype);

        for (int i = 0; i <= _obj.IDNo.Split(',').Length - 1; i++)
        {
            dat.Rows.Add(new object[] { 
                _obj.Name.Split(',')[i].Trim(), 
                _obj.EName.Split(',')[i].Trim(), 
                BLL.Sys.EnumItem.GetTextByValue("IDType", _obj.IDType.Split(',')[i].Trim()), 
                _obj.IDNo.Split(',')[i].Trim(),
                _obj.Sex.Split(',')[i].Trim().Replace("1", "女").Replace("0", "男"),
                _obj.Birtyday.Split(',')[i].Trim(),
                _obj.Age.Split(',')[i].Trim()
            });
        }

        rptPolicyholders.DataSource = dat;
        rptPolicyholders.DataBind();
    }
    #endregion

    #region 转发邮件
    void FowardingTo()
    {
        string emaillist = RequestBase.GetFormString("emaillist");
        string objectid = RequestBase.GetFormString("objectid");

        if (emaillist.Split(',').Length <= 0)
        {
            BLL.AjaxHelper.ResponseWrite("邮件地址有误，操作失败！");
        }
        else
        {
            string res = (new BLL.Insurance.InsurancePolicyBase()).Forwarding(objectid, emaillist.Split(','));
            BLL.AjaxHelper.ResponseWrite("succeeded");
        }
    }
    #endregion

    #region 发送快递信息
    void SendShipmentNotice()
    {
        Model.ShipmentProgressBase _obj = new Model.ShipmentProgressBase();
        _obj.Notice = "保单快递通知";
        _obj.NoticeType = RequestBase.GetFormString("noticetype");
        _obj.NoticeContent = RequestBase.GetFormString("noticecontent").Replace("expressnumber", RequestBase.GetFormString("shipmentnumber"));
        _obj.ShipmentNumber = RequestBase.GetFormString("shipmentnumber");
        _obj.ShipmentDate = DateTime.Parse(RequestBase.GetFormString("shipmentdate"));
        _obj.ShipmentType = RequestBase.GetFormString("shipmenttype");
        _obj.Email = RequestBase.GetFormString("email");
        _obj.Phone = RequestBase.GetFormString("phone"); 
        _obj.StatusCode = 0;
        _obj.RegardingObjectId = RequestBase.GetFormString("objectid");
        _obj.RegardingObjectName = "申根旅行险保单";
        _obj.ProgressName = string.Format("申根旅行保险保单[{0}]快递发送提醒", RequestBase.GetFormString("ordernumber"));

        string res = (new BLL.ShipmentProgressBase()).Add(_obj);
        if (res.IndexOf("succeeded") >= 0)
        {
            string shipmentprogressid = res.Split('|')[1];
            try
            {
                if (_obj.NoticeType.IndexOf("1") >= 0)
                {
                    string recitemslist = SmtpMail.EmailFactory.MailToGroup(
                        new string[] { RequestBase.GetFormString("email") },
                        null,
                        "www.mapfre-assistance.com.cn",
                        ConfigurationManager.AppSettings["Email"].ToString(),
                        ConfigurationManager.AppSettings["EmailPassword"].ToString(),
                        _obj.ProgressName,
                        _obj.NoticeContent,
                        ConfigurationManager.AppSettings["SmtpServer"].ToString(),
                        25);
                    res = "succeeded";
                }

                if (res.IndexOf("succeeded") >= 0)
                {
                    if (_obj.NoticeType.IndexOf("2") >= 0)
                    {
                        sms_webservice.SmsWebService _wbss = new sms_webservice.SmsWebService();
                        sms_webservice.SmsMessage _smsObj = new sms_webservice.SmsMessage();
                        _smsObj.PhoneNumbers = _obj.Phone.Split(',');
                        _smsObj.OrderNumber = RequestBase.GetFormString("ordernumber");
                        _smsObj.SmsContent = _obj.NoticeContent;
                        _smsObj.CreatedBy = new Guid(this.SystemUserId);
                        _smsObj.SmsId = "";

                        _obj.StatusCode = (new sms_webservice.SmsWebService().SendSMS(_smsObj).Trim().ToLower() == "failed") ? -1 : 1;
                        res = (_obj.StatusCode == 1) ? "succeeded" : "发送失败！";
                    }
                    else
                    {
                        _obj.StatusCode = 1;
                        res = "succeeded";
                    }
                    _obj.ShipmentProgressId = shipmentprogressid;
                    (new BLL.ShipmentProgressBase()).Update(_obj);
                    BLL.Insurance.InsurancePolicyBase.UpdateStatus(RequestBase.GetFormString("ordernumber"), this.SystemUserId, 2);
                }
            }
            catch(Exception err)
            {
                res = err.Message;
            }
        }
        BLL.AjaxHelper.ResponseWrite(res);
    }
    void LoadShipmentList()
    {
        try
        {
            string SQL = " AND RegardingObjectId = '" + RequestBase.GetFormString("objectid") + "'"; 

            Control uc_rep = LoadControl("~/website_admin/insurance/_controls/ctlOrderList.ascx");

            Repeater rptShipmentList = (Repeater)uc_rep.FindControl("rptShipmentList");

            DataTable dat = BLL.CommonBLL.Select("ShipmentProgressBase", "*", SQL + " ORDER BY ShipmentDate ASC");
              
            rptShipmentList.DataSource = dat;
            rptShipmentList.DataBind();

            StringBuilder strb = new StringBuilder();
            StringWriter sw = new StringWriter(strb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            rptShipmentList.RenderControl(htw);

            BLL.AjaxHelper.ResponseWrite(strb.ToString());
        }
        catch (System.Threading.ThreadAbortException err)
        {
            //nothing   to   do   
        }
        catch (Exception err)
        {
            BLL.AjaxHelper.ResponseWrite(err.Message);
        }
    }
    #endregion
}